<template>
	<view :id="templateId" v-if="loaded">
		<!-- 地址 -->
		<navigator
			url="/pages/user/pages/address/addressList?source=1"
			class="page-panel address-section"
			>
			<view class="address-content">
				<uni-icon
					:color="themeStyles.lightMainColor"
					name="address-full"
					size="60rpx"
				>
				</uni-icon>
				<view class="cen">
					<view class="top">
						<text class="name">{{
							addressData.customerName || ""
						}}</text>
						<text class="mobile">{{
							addressData.phone || ""
						}}</text>
					</view>
					<text class="address">{{ addressData.address || "" }}</text>
				</view>
				<uni-icon name="right" size="26rpx"> </uni-icon>
			</view>
		</navigator>
		<!-- 商品信息简介 -->
		<view class="goods-section">
			<view class="goods-list">
				<!-- 
					v-for="(item, index) in orderInfo.orderGoodsList"
					:key="index"
					:goodsPrice="item.priceStr.split('.')"
					:latePrice="item.priceOut" -->
				<uni-goods-col
					:goods="goodsDetail"
					:routeLink="
						`/pages/common/pages/goods/goodsDetail?goodsId=${item.goodsId}`
					"
				>
					<view slot="metaLeft">
						<view 
							class="fs28 lh40"
							:style="themeStyles.textMainColor">200积分</view>
					</view>
					<view slot="metaRight">
						<view class="cut-num">x1</view>
					</view>
				</uni-goods-col>
			</view>
			<!-- <view class="goods-total">
				<text>商品金额：</text>
				<view
					class="goods-total-price"
					:style="themeStyles.textMainColor"
				>
					<text class="price">{{
						orderInfo.goodsPriceTotal[0]
					}}</text>
					<text class="decimal">{{
						orderInfo.goodsPriceTotal[1] || "00"
					}}</text>
				</view>
			</view> -->
		</view>
		<!-- 积分金额明细 -->
		<view class="price-section">
			<!-- 金额明细 begin -->
			<view class="yt-list">
				<!-- <view
          v-if="!buyData.actId"
          class="df jc-sb yt-list-cell discount"
          @click="toggleCouponListPop(1)"
        >
          <view class="df df-r">
            <text class="cell-tit clamp">优惠券</text>
          </view>
          <template>
            <text
              v-if="orderInfo.couponRemission > 0"
              class="cell-right"
            >-￥{{orderInfo.couponRemission}}</text>
            <view
              v-else
              class="df jc-c ai-c cell-right"
            ><text>选择优惠券</text>
              <uni-icon
                name="right"
                size="34rpx"
              ></uni-icon>
            </view>
          </template>
        </view> -->

				<view v-if="!buyData.actId" class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">消耗积分</text>
					<text class="cell-right">200</text>
				</view>

				<view class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">运费</text>
					<text class="cell-right">{{
						(orderInfo.freightFee && `￥${orderInfo.freightFee}`) ||
							"快递免邮"
					}}</text>
				</view>

				<view class="df jc-sb yt-list-cell">
					<text class="cell-tit clamp">合计</text>
					<text class="cell-right">￥10.00</text>
				</view>
			</view>
			<!-- 金额明细 end -->
		</view>

		<!-- 底部 -->
		<view class="footer zz-flex zz-jc-fe zz-ai-c">
			<view class="price-total-box">
				<view class="price-total-name">实付金额：</view>
				<view
					:style="themeStyles.textMainColor"
					class="price-total-content"
				>
					<text class="price">{{ orderInfo.totalFee[0] }}</text>
					<text class="decimal">{{
						orderInfo.totalFee[1] || "00"
					}}</text>
				</view>
			</view>
			<button
				type="primary"
				:style="themeStyles.btnFullColor"
				class="zz-flex zz-jc-c zz-ai-c btn full"
			>
				提交订单
			</button>
		</view>

		<!-- 优惠券面板 -->
		<view
			class="mask"
			:class="maskState === 0 ? 'none' : maskState === 1 ? 'show' : ''"
			@click="toggleCouponListPop(0)"
			>
			<view class="por mask-content" @click.stop.prevent="stopPrevent">
				<view v-if="!couponList.length" class="tac unavailabel-desc"
					>暂无可以使用的优惠券</view
				>
				<!-- 优惠券页面 -->
				<template v-else>
					<view
						@click.stop="selectCoupon(item.couponCustomerId)"
						class="coupon-item"
						v-for="(item, index) in couponList"
						:key="index"
					>
						<view class="con">
							<view class="left">
								<template>
									<text class="title"
										>{{ item.couponTypeValue }}
									</text>
								</template>
								<text class="time"
									>有效期至{{ item.endTime }}</text
								>
							</view>
							<view
								:style="themeStyles.textAdronmentColor"
								class="right"
							>
								<text
									v-if="item.couponType !== 30"
									class="price"
									>￥{{ item.discounts }}</text
								>
								<text v-else class="price"
									>{{ item.discounts }}折</text
								>
							</view>
							<view class="circle l"></view>
							<view class="circle r"></view>
						</view>
						<text class="tips">{{ item.couponName }}</text>
					</view>
				</template>
			</view>
			<button
				v-if="!!couponCustomerId"
				:style="themeStyles.btnFullColor"
				@click.stop="selectCoupon(null)"
				class="poa btn"
			>
				不使用优惠券
			</button>
		</view>
	</view>
</template>

<script>
/** api begin */
/*  */
import { joinGroup } from "@/lib/api/groupServer/group";

import { queryDefaultAddress } from "@/lib/api/customerServer/address";

//import { addBargainRecord } from "@/lib/api/bargainServer/initiator";

//import { tallyOrder, submitOrder } from "@/lib/api/orderServer/order";
//import { queryCanUseCouponList } from "@/lib/api/couponServer/customer";
/** api end */

import { baseFileUri } from "@/utils/request/baseConfig";

/** components begin */
import uniCountdown from "@/components/uniCountdown/uniCountdown";
import uniGoodsCol from "@/components/goods/uniGoodsCol";
import uniIcon from "@/components/uniIcon/uniIcon";
/** components end */

import payMixin from "@/mixins/pay";
import { mapState, mapMutations } from "vuex";
/** 非页面展示数据 begin */
/** 非页面展示数据 end */

export default {
	mixins: [payMixin],
	components: {
		uniCountdown,
		uniGoodsCol,
		uniIcon
	},

	data() {
		return {
			/* test */
			goodsPrice:[],
			/* test */
			buyData: {},
			couponCustomerId: "",
			orderInfo: null,
			// specDetailId: '',
			// specSkuId: '',
			addressId: "",
			baseFileUri,
			goodsList: [],
			maskState: 0, //优惠券面板显示状态
			couponList: [],
			addressData: {
				customerAddrId: "",
				phone: "",
				address: ""
			}
		};
	},

	computed: {
		/* 积分vuex */
		...mapState("integral",["goodsDetail"]),
		...mapState("activity", ["activityData"])
	},

	onLoad(option) {
		console.log(this.goodsDetail);
		console.log("option", option);
		/* test */
		/* 商品简介图 */
		this.goodsDetail.imagePath = this.goodsDetail.imagePathMain[0];
		/* test */
		//this.buyData = JSON.parse(option.buyData);
		//商品数据
		// let data = JSON.parse(option.data);
		// console.log(data);
		//this.onTallyOrder();
	},

	async onShow() {
		try {
			/* 获取地址信息 */
			await this.onQueryDefaultAddress()
		} catch (error) {
			
		}
		// this.onTallyOrder();
		/* 显示页面 */
		this.loaded = true;
	},

	methods: {
		// 选择优惠券
		/* async selectCoupon(couponCustomerId) {
			this.couponCustomerId = couponCustomerId;
			await this.onTallyOrder();
			this.maskState = 0;
		}, */
		/**
		 * @param { Number } type   // 优惠券列表 1: 显示 0: 隐藏
		 */
		async toggleCouponListPop(type) {
			if (type === 1) {
				this.couponList = await this.getCouponList();
			}
			this.maskState = type;
		},

		// 获取可用优惠券列表
		/* getCouponList() {
			const buyData = this.buyData;

			const propsData = {
				// good_id: this.orderInfo.orderid,
				cartIds: (buyData.cartIds && buyData.cartIds) || "",
				number: buyData.num,
				skuId: buyData.skuId
			};
			return queryCanUseCouponList(propsData).then(res => {
				return res.data;
			});
		}, */

		// 跳转到商品详情页
		navToOrderProduct(goodsId) {
			uni.navigateTo({
				url: `/pages/common/pages/goods/goodsDetail?goodsId=${goodsId}`
			});
		},

		// 订单结算数据
		async onTallyOrder() {
			return await Promise.resolve()
			/** 地址相关 begin */
			try {
				await this.onQueryDefaultAddress();
			} catch (error) {
				console.log("error", error);
				const modalData = {
					content: "请选择您的收货地址",
					showCancel: true
				};
				try {
					await this.$api.showModal(modalData);
					this.navTo(
						`/pages/user/pages/address/addressList?source=${1}`
					);
					return;
				} catch (modelError) {
					console.log("modelError", modelError);
					await this.$api.showToast(
						modelError.resultInfo || "出错了，请重试*_*"
					);
					uni.navigateBack();
					return;
				}
			}
			/** 地址相关 end */

			/** 结算 begin */
			const buyData = this.buyData;
			const propsData = this.processOrderPropsData();
			console.log("propsData", propsData);
			try {
				const res = await tallyOrder(propsData);

				// this.orderInfo.orderGoodsList.forEach((item, index) => {
				//   this.orderInfo.orderGoodsList[index].price = item.priceStr.split(".");
				// });

				// res.data.orderGoodsList = this.splitGoodsPrice(
				//   res.data.orderGoodsList,
				//   "price",
				//   "priceStr"
				// );

				res.data.goodsPriceTotal = `${res.data.goodsPriceTotal}`.split(
					"."
				);
				this.orderInfo = res.data;

				this.orderInfo.totalFee = `${this.orderInfo.totalFee}`.split(
					"."
				);
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "操作失败");
				uni.navigateBack();
				return;
			}
			/** 结算 end */

			this.loaded = true;
		},

		// 处理结算参数
		processOrderPropsData() {
			const buyData = this.buyData;
			const basePropsData = {
				cartIdList:
					(buyData.cartIds && buyData.cartIds.split(",")) || [],
				customerAddrId: this.addressData.customerAddrId || "",
				couponCustomerId: this.couponCustomerId || "",
				skuId: buyData.skuId,
				buyNumber: buyData.num
			};

			const activityPropsData = {};

			switch (buyData.actType) {
				case 10:
					activityPropsData.groupId = buyData.actId;
					activityPropsData.groupTeamId =
						(buyData.actId && this.activityData.joinActivityId) ||
						"";
				case 20:
					activityPropsData.bargainId = buyData.actId;
				default:
			}

			// 组合结算活动商品需要的参数
			return Object.assign({}, basePropsData, activityPropsData);
		},

		// 查询默认地址
		onQueryDefaultAddress() {
			if (this.addressData.customerAddrId) return;

			return queryDefaultAddress().then(res => {
				this.addressData = res.data;
			});
		},

		// 提交
		async onSubmitOrder() {
			const hasOrder = this.buyData.actType !== 20;
			if (hasOrder) {
				this.onCreateOrder();
			} else {
				this.onCreateActiviryRecord();
			}
		},

		// 创建活动记录
		async onCreateActiviryRecord() {
			try {
				const joinId = await this.createBargainRecord();
				setTimeout(() => {
					uni.reLaunch({
						url: `/pages/activity/pages/bargain?joinId=${joinId}`
					});
				}, 300);
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "提交失败 * _ *");
			}
		},

		// 创建砍价记录
		/* createBargainRecord() {
			const buyData = this.buyData;
			const propsData = {
				bargainId: buyData.actId,
				skuId: buyData.skuId,
				customerAddrId: this.addressData.customerAddrId || ""
			};
			return addBargainRecord(propsData).then(res => {
				return res.data.bargainInitiatorId;
			});
		}, */

		// 创建订单
		async onCreateOrder() {
			// 判断是否是拼团单
			const groupActivity = this.buyData.actType === 10;
			let orderId = "";
			let routeLink = "";
			try {
				orderId = await this.createGeneralOrder();
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "操作失败");
				return;
			}

			try {
				await this.onPay(orderId);
				if (!groupActivity) {
					setTimeout(() => {
						routeLink = "/pages/user/pages/order/orderList";
						uni.reLaunch({ url: routeLink });
					}, 300);
				} else {
					setTimeout(() => {
						if (this.activityData.joinActivityId) {
							routeLink = `/pages/activity/pages/group?joinId=${this.activityData.joinActivityId}`;
						} else {
							routeLink = "/pages/activity/pages/myGroup";
						}
						uni.reLaunch({
							url: routeLink
						});
					}, 300);
				}
			} catch (error) {
				console.log("error", error);
				await this.$api.showToast(error.resultInfo || "支付失败");
				setTimeout(() => {
					uni.reLaunch({ url: "/pages/user/pages/order/orderList" });
				}, 300);
			}
		},

		// 创建活动订单
		async createActivityOrder() {
			// 判断是否是拼团单
			//   const groupActivity = this.buyData.actType === 10;
			//   let orderId = "";
			//   try {
			//     orderId = await this.createGeneralOrder();
			//   } catch (error) {
			//     console.log("error", error);
			//     await this.$api.showToast(error.resultInfo || "操作失败");
			//     return;
			//   }
			//   try {
			//     await this.onPay(orderId);
			//     switch (this.buyData.actType) {
			//       case 10:
			//         setTimeout(() => {
			//           uni.reLaunch({
			//             url: `/pages/activity/pages/myGroup`
			//           });
			//         }, 300);
			//         break;
			//       default:
			//         break;
			//     }
			//   } catch (error) {
			//     console.log("error", error);
			//     await this.$api.showToast(error.resultInfo || "支付失败");
			//     setTimeout(() => {
			//       uni.reLaunch({ url: "/pages/user/pages/order/orderList" });
			//     }, 300);
			//   }
		},

		// 创建订单
		/* createGeneralOrder() {
			const propsData = this.processOrderPropsData();
			console.log("propsData", propsData);
			return submitOrder(propsData).then(res => {
				return res.data.orderId;
			});
		}, */

		//显示优惠券面板
		toggleMask(type) {
			let timer = type === "show" ? 10 : 300;
			let state = type === "show" ? 1 : 0;
			this.maskState = 2;
			setTimeout(() => {
				this.maskState = state;
			}, timer);
		},

		numberChange(data) {
			this.number = data.number;
		},

		changePayType(type) {
			this.payType = type;
		},

		stopPrevent() {}
	}
};
</script>

<style lang="scss">
// 订单样式
@import "@/common/styles/order/orderDetail.scss";

.goods-section {
	padding-bottom: 20rpx;
}

/* 优惠券面板 */
.mask {
	display: flex;
	align-items: flex-end;
	position: fixed;
	left: 0;
	top: var(--window-top);
	bottom: 0;
	width: 100%;
	background: rgba(0, 0, 0, 0);
	z-index: 9995;
	transition: 0.3s;

	.mask-content {
		width: 100%;
		min-height: 30vh;
		max-height: 70vh;
		padding-bottom: 96rpx;
		background: #f3f3f3;
		transform: translateY(100%);
		transition: 0.3s;
		overflow-y: scroll;
	}

	.unavailabel-desc {
		margin-top: 40rpx;
		font-weight: blod;
		font-size: $theme-size-large-base;
		color: $theme-color-main-base;
	}

	&.none {
		display: none;
	}

	&.show {
		background: rgba(0, 0, 0, 0.4);

		.mask-content {
			transform: translateY(0);
		}
	}
	.btn {
		left: 0;
		right: 0;
		bottom: 0;
		height: 96rpx;
		line-height: 96rpx;
		color: #fff;
		font-size: 32rpx;
	}
}

/* 优惠券列表 */
.coupon-item {
	display: flex;
	flex-direction: column;
	margin: 20rpx 24rpx;
	background: #fff;

	.con {
		display: flex;
		align-items: center;
		position: relative;
		height: 120rpx;
		padding: 0 30rpx;

		&:after {
			position: absolute;
			left: 0;
			bottom: 0;
			content: "";
			width: 100%;
			height: 0;
			border-bottom: 1px dashed #f3f3f3;
			transform: scaleY(50%);
		}
	}

	.left {
		display: flex;
		flex-direction: column;
		justify-content: center;
		flex: 1;
		overflow: hidden;
		height: 100rpx;
	}

	.title {
		font-size: 32rpx;
		color: $theme-color-main-base;
		margin-bottom: 10rpx;
	}

	.time {
		font-size: 24rpx;
		color: $theme-color-ghost-base;
	}

	.right {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
		height: 100rpx;
	}

	.price {
		font-size: 44rpx;
	}

	.tips {
		font-size: 24rpx;
		color: $theme-color-main-base;
		line-height: 60rpx;
		padding-left: 30rpx;
	}

	.circle {
		position: absolute;
		left: -6rpx;
		bottom: -10rpx;
		z-index: 10;
		width: 20rpx;
		height: 20rpx;
		background-color: #f3f3f3;
		border-radius: 200rpx;

		&.r {
			left: auto;
			right: -6rpx;
		}
	}
}
</style>
